'''
Author: duliang thinktanker@163.com
Date: 2024-03-10 11:42:55
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-06-23 16:26:27
FilePath: \biliweb\douyin.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import logging
import requests
import cv2
from rapidfuzz import fuzz
import random
# import sys
# from multiprocessing import Process, Queue
import re
from threading import Thread
import subprocess
# 屏蔽airtest的logger信息
logging.getLogger("airtest").setLevel(logging.ERROR)
# 创建一个logger
logger = logging.getLogger("抖音")
logger.setLevel(logging.DEBUG)


def get_devices_list():
    """获取所有在线设备

    Returns:
        _type_: 设备列表
    """
    res = subprocess.run("adb devices",
                         capture_output=True,
                         text=True,
                         shell=True)
    # print(res.stdout, res.stderr)
    result = res.stdout
    result = result.splitlines()[1:]
    logger.info(result)
    devices_list = []
    for res in result:
        device = res.split('\t')[0]
        if device != '':
            devices_list.append(device)
    return devices_list


# # 设备的IP地址和ADB端口号
# device_ip = "192.168.15.34"  # 替换成实际的手机IP地址
# adb_port = 5555  # 默认ADB端口号，如果修改过请替换为实际端口号
# android = Android(device_sn=device_ip + ":" + str(adb_port),
#                   cap_method="JAVACAP",
#                   touch_method="ADBTOUCH",
#                   ori_method="ADBORI")
# android.wake()
# currentDevice = android.get_default_device()
# page_name = ""
#
# adb shell rm /data/local/tmp/mini*
# dev = connect_device("android:///")
# dev = connect_device(
#     f"android://127.0.0.1:5037/{currentDevice}?cap_method=javacap&touch_method=adb"  #?cap_method=javacap&touch_method=adb
# )

# dev = connect_device(
#     f"android://127.0.0.1:5037/LMG710N5a60f67b"  #?cap_method=javacap&touch_method=adb
# )
# dev = connect_device(
#     f"android://127.0.0.1:5037/LMG710N5a60f67b"  #?cap_method=javacap&touch_method=adb
# )
# adb tcpip 5555
# dev = connect_device(
#     f"android://127.0.0.1:5037/192.168.15.34:5555?cap_method=JAVACAP^&^&ori_method=ADBORI"  #?cap_method=javacap&touch_method=adb
# )

# poco1 = AndroidUiautomationPoco(device=dev,
#                                 use_airtest_input=True,
#                                 screenshot_each_action=False)
'''
瞎刷的优先级：
1、商城
2、视频
3、小说
4、直播
'''


def max_option_match(input_string: str, string_list: list):
    # 初始化最大匹配度和索引
    max_match_ratio = 0
    max_match_index = -1

    for index, compare_string in enumerate(string_list):
        # 使用fuzz.ratio方法计算两个字符串的匹配度
        match_ratio = fuzz.ratio(input_string, compare_string)

        # 如果当前匹配度大于已记录的最大匹配度，则更新最大匹配度和索引
        if match_ratio > max_match_ratio:
            max_match_ratio = match_ratio
            max_match_index = index
    # 返回匹配率和index
    return max_match_ratio, max_match_index


class douyin():
    def __init__(self, dev):
        ###################初始化###################
        self.dev = connect_device(
            f"android://127.0.0.1:5037/{dev}"  #?cap_method=javacap&touch_method=adb
        )

        # if dev:
        self.dev.wake()
        # stop_app("com.ss.android.ugc.aweme.lite")
        start_app("com.ss.android.ugc.aweme.lite")
        # sleep()
        self.poco = AndroidUiautomationPoco(device=self.dev,
                                            use_airtest_input=True,
                                            screenshot_each_action=False)
        self.width, self.height = self.poco.get_screen_size()
        self.start_point = (self.width / 5, self.height * 0.8)  # 中点偏上位置
        self.end_point = (self.width / 5, self.height * 0.3)  # 中点偏下位置
        self.start_point_1 = (self.width / 5, self.height * 0.6)  # 中点偏上位置
        self.end_point_1 = (self.width / 5, self.height * 0.5)  # 中点偏下位置
        self.left_point = (self.width * 0.2, self.height / 2)
        self.right_point = (self.width * 0.8, self.height / 2)
        self.first_start = True
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(f"./log/{dev.replace('.','')}_log.txt",
                                 encoding="utf-8")
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)  # 设置控制台日志级别
        # 定义handler的输出格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        logger.info(dev)
        ################### poco ###################
        self.text_click_list = [
            '取消',
            '我知道了',
            '看小说',
            # '领金币',#开启这个会在首页的时候点那个小按钮导致死循环
            '领取奖励',
            # '继续观看',
            '领取成功，关闭，按钮',
            "开心收下",
            "忽略提醒"
        ]
        self.textMatches_click_list = [r"领取.*?金币", r".*?视频再.*?金币"]
        # 目标金币
        self.target_coin = 0
        self.video_coin = 10000
        self.novel_score = 30
        # 判断是否已经获取 瞎刷 时间防止线程重复开启
        self.have_value = False
        # 去逛街
        self.go_shopping = False

        ################### ocr ###################
        self.page_text = []
        self.box = []
        self.touch_back_list = ["邀请好友立赚高额现金", "赠送"]
        # self.touch_2_back_list = ["点击立得", "开宝箱得金币"]
        self.touch_list = []
        self.wastetime_value = 0
        self.wastetime_task_begin = False
        self.timeout = 20

        ################### 瞎刷 ###################
        self.shop = False
        self.video = False
        self.video_done = False
        self.novel = False
        self.novel_done = False
        self.live = False
        self.live_done = False

        ################### 搜索 ###################
        self.search = False
        ################### 送好友 #################
        self.give_coin = False
        ################### 小岛 ###################
        #  在小岛
        self.time_island = ""
        self.in_island = False
        self.next_island_time = 0
        self.islandClick = False
        # 任务是否做完
        # self.island_done = False
        ################### 友友 ###################
        self.youyou = False
        # 看直播
        self.watching_live = False
        # 广告
        self.guanggao = False
        # 吃饭打卡
        self.chifan = False
        # 换一换只换一次
        self.change_one_time = False
        # 判断是否页面卡死
        self.lastOCRtext = ''
        self.repeatCount = 0

    def ocr_page(self):
        screen = self.dev.snapshot()
        # 灰度图
        gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
        # 二值化
        _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
        # cv2.imshow("Image Window", screen)
        # cv2.imshow("binary", binary)
        cv2.imwrite("./img/binary.png", binary)
        # cv2.imwrite("screen.png", screen)
        # # 腐蚀、膨胀
        # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        # dilated = cv2.dilate(binary, kernel, iterations=1)
        # eroded_img = cv2.erode(binary, kernel, iterations=1)
        ret, img_bytes = cv2.imencode(
            ".png", binary, [cv2.IMWRITE_JPEG_QUALITY, 50])  # 将裁剪的cv2格式转成jpg
        image_in_bytes = img_bytes.tobytes()
        # screen = cv2.imread("screen.png")
        # with open("binary.png", "rb") as f:
        #     image_in_bytes = f.read()
        resp = requests.post(url='http://127.0.0.1:8211/ocr',
                             files={"imgbin": image_in_bytes})
        resp_json = resp.json()
        ocrText, box = resp_json
        # ocrText = resp_json[0]
        similarity = fuzz.ratio(''.join(ocrText), ''.join(self.lastOCRtext))
        # if ocrText == self.lastOCRtext:
        if similarity > 90:
            self.repeatCount += 1
            if self.repeatCount >= 3:
                logger.info("页面卡死")
                keyevent("back")
                self.repeatCount = 0
        else:
            self.repeatCount = 0
            self.lastOCRtext = ocrText
        logger.debug(ocrText)
        for i in range(len(box)):
            # logger.info(temp0[i], temp1[i])
            top_left_x = int(box[i][0][0])
            top_left_y = int(box[i][0][1])
            bottom_right_x = int(box[i][2][0])
            bottom_right_y = int(box[i][2][1])
            # logger.info((top_left_x, top_left_y), (bottom_right_x, bottom_right_y),
            #       raw_list[i])
            cv2.rectangle(screen, (top_left_x, top_left_y),
                          (bottom_right_x, bottom_right_y), (0, 255, 0), 2)
            cv2.imwrite("./img/screen.png", screen)
        return resp_json

    def poco_judge_page(self) -> bool:
        """
        利用poco识别
        
        返回值：
        
        True  导致ocr识别
        
        False 跳过ocr再次poco识别
        """
        logger.info("使用poco判断页面")

        try:
            freeze_poco = self.poco.freeze()
        except Exception as e:
            logger.error(str(e))
            return False
        # if freeze_poco(text="领券抢购").exists():
        #     logger.info("吃饭打卡页面")
        if freeze_poco(textMatches="再赚最高.*?金币").exists() or freeze_poco(
                textMatches=".*?后.*?领.*?补贴").exists():
            logger.info("吃饭 异常返回")
            keyevent("back")
            self.chifan = False
            return True
        elif freeze_poco(
                textMatches=r'\d+\.\d+分').exists() and not freeze_poco(
                    textMatches='推荐榜.*?').exists():
            logger.info("小说 异常返回")
            keyevent("back")
            self.chifan = False
            return True
        elif freeze_poco("m.l.live.plugin:id/comment_input_layout").exists(
        ) and not self.live:
            # keyevent('back')
            freeze_poco(desc='关闭').click()
            return False
        # 这里会出现两个？一前一后
        elif freeze_poco(textMatches=r'看视频再领.*?金币').exists():
            freeze_poco(textMatches=r'看视频再领.*?金币').click()
            if self.chifan:
                logger.info("完成吃饭打卡")
            return False
        elif freeze_poco(textMatches="领取.*?补贴\d+金币").exists():
            logger.info(freeze_poco(textMatches="领取.*?补贴\d+金币").get_text())
            freeze_poco(textMatches="领取.*?补贴\d+金币").click()
            self.chifan = True
            logger.info("开始吃饭打卡")
            return False
        elif freeze_poco(textMatches='明天签到领.*?金币').exists():
            freeze_poco(textMatches='明天签到领.*?金币').click()
            return False
        elif freeze_poco(text='桌面奖励').exists():
            freeze_poco(text='桌面奖励').click()
            return False
        elif freeze_poco(text='去读书').exists():
            keyevent('back')
            return False
        if freeze_poco(text="去APP赚金币").exists():
            # freeze_poco(text="去APP赚金币").click()
            keyevent("back")
            return False
        if self.chifan:
            # if True:
            if freeze_poco(text='搜索').exists():
                logger.info("在吃饭打卡页面 返回主页")
                self.chifan = False
                keyevent('back')
        if freeze_poco(textMatches='\d+秒').exists() and freeze_poco(
                text='返回').exists():
            logger.info("广告倒计时页面")
            left_poco = self.poco(textMatches='\d+秒')
            left_secs = 0
            if left_poco.exists():
                left_secs = re.findall(r'(\d+)秒', left_poco.get_text())
            if left_secs:
                left_secs = int(left_secs[0])
            logger.info("剩余时间:{}".format(left_secs))
            start = time.time()
            while 1:
                if (time.time() - start) > int(left_secs) + 2:
                    print("↑" * 10)
                    swipe(self.start_point, self.end_point, duration=0.5)
                    try:
                        left_poco = self.poco(textMatches='\d+秒')
                        if left_poco.exists():
                            left_secs = re.findall(
                                r'(\d+)秒',
                                self.poco(textMatches='\d+秒').get_text())
                            if left_secs:
                                left_secs = int(left_secs[0])
                            logger.info("剩余时间:{}".format(left_secs))
                        else:
                            left_secs = 0
                    except Exception as e:
                        left_secs = 1
                        logger.error(e)
                    start = time.time()
                if not self.poco(textMatches=r'\d+秒.*?').exists():
                    logger.info("视频结束")
                    break

        elif freeze_poco(text="已完成").exists():
            freeze_poco(text="已完成").click()
            if freeze_poco(desc="返回").exists():
                freeze_poco(desc="返回").click()
            return False

        elif freeze_poco(text='立即签到').exists():
            freeze_poco(text='立即签到').click()
            return False
        elif freeze_poco('2').exists(
        ) and not self.watching_live and self.novel and not freeze_poco(
                '9').exists() and not self.chifan:
            freeze_poco('2').click()
            start = time.time()
            while 1:
                if self.poco("m.l.novel:id/novel_cover_main_container").exists(
                ) or self.poco(
                        "m.l.novel:id/novel_sdk_ug_reader_task_tip").exists():
                    break
                elif self.poco(text="看小说").exists():
                    self.poco(text="看小说").click()
                    self.poco('3').wait_for_appearance()
                    self.poco('3').click()
                elif self.poco(text="立即签到").exists():
                    self.poco(text="立即签到").click()
            touch((int(self.width * 0.8), int(self.height / 2)))
            return False
        # if self.chifan:

        if freeze_poco(textMatches=r".*?免费下载.*?").exists():
            if self.poco(desc="返回").exists():
                self.poco(desc="返回").click()
                logger.info("广告返回")
                return True
        elif freeze_poco(textMatches=r".*?下载.*?免费.*?").exists():
            if self.poco(desc="返回").exists():
                self.poco(desc="返回").click()
                logger.info("广告返回")
                return True
        elif freeze_poco(text="开心收下").exists():
            freeze_poco(text="开心收下").click()
            logger.info("开心收下")
            return True
        elif freeze_poco(text="提醒我休息").exists():
            freeze_poco(text="取消").click()
        # if freeze_poco(text="搜书名搜作者").exists():
        #     logger.info("当前在读书搜索页面")
        #     # keyevent('back')
        #     return True

        if freeze_poco(textMatches="记录此刻.*?").exists():
            freeze_poco(textMatches="记录此刻.*?").click()
            self.poco(text="发布动态").wait_for_appearance()
            logger.info("当前在发布动态页面")
            while 1:
                if self.poco(text="美滋滋").exists():
                    self.poco(text="美滋滋").click()
                elif self.poco(text="做饭").exists():
                    self.poco(text="做饭").click()
                elif self.poco(text="平静").exists():
                    self.poco(text="平静").click()
                elif self.poco(text="在吃饭").exists():
                    self.poco(text="在吃饭").click()
                else:
                    sleep(2)
                    continue
                while not self.poco(text="发布动态").exists():
                    pass
                self.poco(text="发布动态").click()
                keyevent("back")
                self.in_island = False
                return False
        if self.in_island:
            logger.info("当前在小岛")
            start = time.time()
            while not self.poco(text="规则").exists():
                if time.time() - start > self.timeout:
                    logger.info("小岛载入 超时")
                    self.in_island = False
                    return False
            # sleep(2)
        if freeze_poco(textMatches=".*?开始.*?打卡").exists():
            result = re.findall(
                r'(\d+)',
                freeze_poco(textMatches=".*?开始.*?打卡").get_text())
            self.next_island_time = int(''.join(result))
            logger.info(f"小岛已完成,退出 下次：{self.next_island_time}")
            keyevent("back")
            while self.poco(textMatches=".*?开始.*?打卡").exists():
                pass
            # swipe(self.start_point, self.end_point, 0.5)
            self.in_island = False
            return True
        elif freeze_poco(text="我回家了").exists():
            freeze_poco(text="我回家了").click()
            return False
        elif freeze_poco(text="我睡觉了").exists():
            freeze_poco(text="我睡觉了").click()
            return False
        elif freeze_poco(text="我出门了").exists():
            freeze_poco(text="我出门了").click()
            return False
        elif freeze_poco(text="我起床了").exists():
            freeze_poco(text="我起床了").click()
            return False
        # self.poco(textMatches="记录此刻.*?").wait_for_appearance()
        # start = time.time()
        # while not self.poco(textMatches="记录此刻.*?").exists():
        #     if time.time() - start > self.timeout:
        #         logger.info("记录此刻 超时")
        #         return False
        if freeze_poco(textMatches="记录此刻.*?").exists():
            freeze_poco(textMatches="记录此刻.*?").click()
            self.poco(text="发布动态").wait_for_appearance()
            logger.info("当前在发布动态页面")
            while 1:
                if self.poco(text="美滋滋").exists():
                    self.poco(text="美滋滋").click()
                elif self.poco(text="做饭").exists():
                    self.poco(text="做饭").click()
                elif self.poco(text="平静").exists():
                    self.poco(text="平静").click()
                elif self.poco(text="在吃饭").exists():
                    self.poco(text="在吃饭").click()
                else:
                    sleep(2)
                    continue
                while not self.poco(text="发布动态").exists():
                    pass
                self.poco(text="发布动态").click()
                keyevent("back")
                self.in_island = False
                return False

        # if freeze_poco(text="发布动态").exists():
        #     logger.info("当前在发布动态页面")
        #     if freeze_poco(text="做饭").exists():
        #         freeze_poco(text="做饭").click()
        #     freeze_poco(text="发布动态").click()
        #     return False

        if freeze_poco(text="换一换，按钮").exists() and self.search:
            logger.info("当前在搜索页面")
            while 1:
                logger.info("换一批搜索")
                self.poco(text="换一换，按钮").click()
                search_list = []
                while not self.poco(
                        nameMatches="com.ss.android.ugc.aweme.lite:id/.*?"
                ).exists():
                    pass
                for child in self.poco(
                        nameMatches="com.ss.android.ugc.aweme.lite:id/.*?"
                ).child("android.widget.FrameLayout").children():
                    search_list.append(child.get_text())
                if search_list:
                    logger.info("搜索列表：{}".format(search_list))
                    search_index = search_list.index("换一换，按钮")
                    search_text = search_list[search_index + 1]
                    logger.info("搜索内容：{}".format(search_text))
                    self.poco(text=search_text).click()
                    sleep(2)
                    cv2.imwrite('./img/temp.png', self.dev.snapshot())
                    if self.poco(
                            "com.ss.android.ugc.aweme.search_lite_plugin:id/time_second_tv"
                    ).exists():
                        self.poco(
                            "com.ss.android.ugc.aweme.search_lite_plugin:id/time_second_tv"
                        ).wait_for_disappearance()
                    # # 如果没有积分条则多退一步
                    else:
                        keyevent("back")
                    keyevent("back")
                    keyevent("back")
                    sleep(2)
                    cv2.imwrite('./searchback2times.png', self.dev.snapshot())
            self.search = False
            return False

        if self.search:
            if freeze_poco(desc="搜索"):
                freeze_poco(desc="搜索").click()
                logger.info("等待 进入搜索界面")
                while not self.poco(
                        text="搜索").exists() and self.wastetime_task_begin:
                    sleep(1)
                while 1:
                    if self.poco(text='搜索').exists():
                        self.poco(text='搜索').click()
                        sleep(5)
                    if self.poco(textMatches='浏览.*?秒.*?金币').exists():
                        self.poco(textMatches='浏览.*?秒.*?金币'
                                  ).wait_for_disappearance()
                        keyevent('back')
                        self.poco(text='搜索').wait_for_appearance()
                    else:
                        self.search = False
                        self.poco(desc='返回').click()
                        sleep(1)
                        self.poco(desc='返回').click()
                        self.search = False
                        break

                # self.poco(text="换一换，按钮").wait_for_appearance()
                # self.search = False
                return True
        # 有进度圈的情况下
        if freeze_poco("com.ss.android.ugc.aweme.lite:id/progress").exists():
            # 有搜索栏的情况下
            if freeze_poco(text="搜索，搜索栏").exists():
                logger.info("在商城")
                while self.wastetime_task_begin:
                    sleep(random.randint(3, 5))
                    if self.poco(text="领金币").exists():
                        self.poco(text="领金币").click()
                        self.poco(text="已完成").wait_for_appearance()
                        self.shop = False
                        keyevent("back")
                        sleep(2)
                        keyevent("back")
                    swipe(self.start_point, self.end_point)
                else:
                    print("商城界面 返回开箱子")
                    return False
            else:
                logger.info("在主页")
                # main_page = True
                if not self.wastetime_task_begin and not self.give_coin and not self.search:
                    freeze_poco(
                        "com.ss.android.ugc.aweme.lite:id/progress").click()
                    return False
                elif self.wastetime_task_begin:
                    logger.info("开始看视频")
                    while self.wastetime_task_begin and self.wastetime_value:
                        sleep(random.randint(2, 5))
                        print("↑" * 10)
                        if self.poco(text="累了吧，休息一下").exists():
                            self.poco(text="取消").click()
                            logger.info("取消 休息一下")
                        if self.poco(text="忽略提醒").exists():
                            self.poco(text="忽略提醒").click()
                            logger.info("忽略提醒")
                        keyevent('back')
                        swipe(self.start_point, self.end_point)
                    else:
                        if not self.wastetime_task_begin:
                            print('视频界面 返回开箱子')
                        return False
        else:
            for t in self.text_click_list:
                if freeze_poco(text=t).exists():
                    logger.info('poco点击：' + freeze_poco(text=t).get_text())
                    freeze_poco(text=t).click()
                    return False
        if freeze_poco(text="继续观看").exists() and not self.guanggao:
            freeze_poco(text="继续观看").click()
            return False
        if freeze_poco(text='继续浏览').exists():
            freeze_poco(text='继续浏览').click()
            return False

        if freeze_poco(text="搜索，搜索栏").exists() and self.shop:
            logger.info("在商城")
            if self.poco(textMatches=r'\d+秒').exists():
                secs = self.poco(textMatches=r'\d+秒').get_text()
                secs = int(secs[:-1])
                print(secs)
                while True:
                    if self.poco(text="领金币").exists():
                        self.poco(text="领金币").click()
                        self.poco(text="已完成").wait_for_appearance()
                        self.shop = False
                        keyevent("back")
                        sleep(2)
                        keyevent("back")
                        return
                    else:
                        swipe(self.start_point, self.end_point)
                        sleep(1)
                        swipe(self.end_point, self.start_point)
                        sleep(1)

        if freeze_poco(textMatches=".*?后.*?补贴").exists():
            keyevent('back')
            logger.info("在主页 2")
            return False

        if freeze_poco(textMatches=r'\d+秒后可领奖励，关闭，按钮').exists() or (
                freeze_poco(textMatches='\d+秒.*?').exists()
                and freeze_poco(text='返回').exists()):
            logger.info("视频倒计时页面")
            left_secs = re.findall(
                r'(\d+)秒',
                freeze_poco(textMatches=r'\d+秒.*?').get_text())
            if left_secs:
                left_secs = int(left_secs[0])
            logger.info("剩余时间:{}".format(left_secs))
            start = time.time()
            while self.wastetime_task_begin:
                if (time.time() - start) > int(left_secs) + 2:
                    print("↑" * 10)
                    swipe(self.start_point, self.end_point, duration=0.5)
                    try:
                        left_secs = re.findall(
                            r'(\d+)秒',
                            self.poco(textMatches=r'\d+秒.*?').get_text())
                        if left_secs:
                            left_secs = int(left_secs[0])
                        logger.info("剩余时间:{}".format(left_secs))
                    except Exception as e:
                        left_secs = 1
                        logger.error(e)
                    start = time.time()
                if not self.poco(textMatches=r'\d+秒.*?').exists():
                    logger.info("视频结束")
                    keyevent('back')
                    break
            self.guanggao = False
            return False

        # 关闭广告
        if freeze_poco("m.l.novel:id/novel_bottom_banner_close").exists():
            freeze_poco("m.l.novel:id/novel_bottom_banner_close").click()
        elif freeze_poco(text="立即下载").exists():
            keyevent("back")
            return False

        if self.novel and not self.novel_done:
            if freeze_poco(
                    "m.l.novel:id/novel_sdk_ug_reader_task_tip").exists():
                logger.info("在小说页面")
                time_value_list = []
                while self.wastetime_task_begin and self.wastetime_value:
                    if self.poco(textMatches=".*?下一页.*?").exists():
                        sleep(6)
                        self.poco(textMatches=".*?下一页.*?").click()
                        logger.info("跳过广告")
                    while not self.poco(
                            "m.l.novel:id/novel_sdk_ug_reader_task_tip"
                    ).exists():
                        pass
                    # if self.poco("m.l.novel:id/text_count_down").exists():
                    #     self.poco("m.l.novel:id/text_count_down").click()
                    self.poco(
                        "m.l.novel:id/novel_sdk_ug_reader_task_tip").click()
                    start = time.time()
                    while not self.poco(text='阅读赚金币').exists():
                        if self.poco(text="立即签到").exists():
                            self.poco(text="立即签到").click()
                        if self.poco("debug").exists():
                            keyevent("back")
                        if time.time() - start > self.timeout:
                            logger.error("看小说赚金币界面超时")
                            return False
                    # cv2.imwrite('./img/reading2.png', dev.snapshot())
                    swipe(self.start_point, self.end_point)
                    time_value_elments = self.poco(
                        "m.l.novel:id/tv_time_value")
                    cur_value_list = []
                    for v in time_value_elments:
                        cur_value_list.append(v.get_text())
                    if time_value_list != cur_value_list:
                        time_value_list = cur_value_list
                        logger.info(cur_value_list)
                    if self.poco(text='去签到').exists():
                        self.poco(text='去签到').click()
                        self.poco(text='立即签到').wait_for_appearance()
                        self.poco(text='立即签到').click()
                        self.poco(
                            textMatches='明天签到领.*?金币').wait_for_appearance()
                        self.poco(textMatches='明天签到领.*?金币').click()

                    if self.poco(text='去领取').exists():
                        logger.info("poco领取金币")
                        self.poco(text='去领取').click()
                        if self.poco(text='我知道了').exists():
                            self.poco(text='我知道了').click()
                        # while not self.poco(
                        #         textMatches=r'看视频再领.*?金币').exists():
                        #     pass
                        # self.poco(textMatches=r'看视频再领.*?金币').click()
                        while not self.poco(text="阅读赚金币").exists():
                            if self.poco(text="继续观看").exists():
                                self.poco(text="继续观看").click()
                            if self.poco(textMatches=r'\d+秒.*?').exists():
                                pass
                            else:
                                keyevent('back')
                                sleep(3)
                    if not f'{self.novel_score}分钟' in cur_value_list:
                        self.novel = False
                        self.novel_done = True
                        keyevent('back')
                        break
                    keyevent('back')
                    sleep(random.randint(8, 15))
                    touch((int(self.width * 0.8), int(self.height / 2)))
                else:
                    if not self.wastetime_task_begin:
                        print("小说界面 返回开箱子")
                keyevent('back')
                if self.poco(text="以后再说").exists():
                    self.poco(text="以后再说").click()
                keyevent('back')
                return True
        if self.watching_live:
            if self.live and freeze_poco(
                    "m.l.live.plugin:id/emoji_entry").exists():
                logger.info("在直播界面")
                start_time = 0
                wait_time = 0
                while self.wastetime_task_begin and self.wastetime_value:
                    print("等待宝箱开启", end='\r')
                    if start_time and wait_time:
                        print('等待时间： ', wait_time - (time.time() - start_time))
                    freeze_poco = self.poco.freeze()
                    if freeze_poco(text='领金币').exists():
                        logger.info("领金币")
                        freeze_poco(text='领金币').click()
                    elif freeze_poco(textMatches="还可做任务赚.*?").exists():
                        logger.info("还可做任务赚")
                        freeze_poco(textMatches="还可做任务赚.*?").click()
                    elif freeze_poco(text='开宝箱').exists():
                        logger.info("开宝箱")
                        freeze_poco(text='开宝箱').click()
                        # while 1:
                    elif freeze_poco(textMatches='赠送.*?').exists():
                        logger.info("赠送，返回")
                        keyevent("back")
                        self.poco("赠送").wait_for_disappearance()
                    elif freeze_poco(text='去Ta直播间').exists():
                        logger.info("去Ta直播间，返回")
                        keyevent('back')
                        self.poco("去Ta直播间").wait_for_disappearance()
                    elif freeze_poco(textMatches="\d+:\d+后可开").exists():
                        wait_time = re.findall(
                            r'\d+',
                            freeze_poco(textMatches="\d+:\d+后可开").get_text())
                        if len(wait_time) > 1:
                            wait_time = int(wait_time[0]) * 60 + int(
                                wait_time[1])
                        else:
                            wait_time = int(wait_time[0])
                        logger.info(f"看直播 等待{wait_time}秒")
                        start_time = time.time()
                        # sleep(wait_time + 2)
                    sleep(1)
                else:
                    if not self.wastetime_task_begin:
                        print("直播界面 返回开箱子")
                    keyevent('back')
            return True
        # elif freeze_poco("").exsits():
        #     logger.info("在商城界面")

        # 正则匹配点击
        for p in self.textMatches_click_list:
            if freeze_poco(textMatches=p).exists():
                logger.info(freeze_poco(textMatches=p).get_text())
                freeze_poco(textMatches=p).click()
                return False
        # # 点击后直接返回
        # for p in self.click_back_list:
        #     if freeze_poco(textMatches=p).exists():
        #         logger.info(freeze_poco(textMatches=p).get_text())
        #         keyevent("back")
        #         return False

        if freeze_poco(textMatches=r".*?\+金币").exists():
            # logger.info(freeze_poco(textMatches=r".*?\+金币").get_text())
            temp_coin = re.findall(
                r"\d+",
                freeze_poco(textMatches=r".*?\+金币").get_text())
            if temp_coin:
                try:
                    temp_coin = int(temp_coin[0])
                except Exception as e:
                    logger.error(e)
                    temp_coin = 0
                if temp_coin != target_coin:
                    logger.info(f"金币发生变化，更新目标金币 {temp_coin}")
                    target_coin = temp_coin
        return True

    def ocr_judge_page(self):
        """
        利用ocr识别
        
        返回值：
        
        休眠时间,是否滑动 
        """
        logger.info("使用ocr判断页面")
        now = int(time.strftime("%H%M", time.localtime()))
        if self.next_island_time:
            if self.next_island_time - 1200 < 0:
                if now > 1200:
                    now = now - 2400
            if now >= self.next_island_time:
                self.islandClick = True
        else:
            self.islandClick = True
        logger.info(f"->瞎刷<- -->{self.wastetime_task_begin}<--")
        print("$" * 80)
        if self.video_done and self.novel_done and self.live_done:
            print("看视频、看小说、看直播 预设任务已完成")
        else:
            print("逛商场", self.shop, "看视频", self.video, "看小说", self.novel,
                  "看直播", self.live)
        print("$" * 80)
        self.page_text, self.box = self.ocr_page()
        page_str = ''.join(self.page_text)
        if self.search:  #如何判断已经完成呢？
            if "换一换" in page_str or "猜你想搜" in page_str:
                logger.info("猜你想搜")
                return 0, False
            elif "重复搜索不能" in page_str:
                logger.info("搜索切换中")
                return 2, False
        if "Thinktank 来了" in page_str:
            logger.info("在直播间,返回主页")
            keyevent('back')
            return 2, False
        elif '开始游戏' in page_str or '退出游戏' in page_str:
            logger.info("在游戏界面,退出")
            keyevent('back')
            return 2, False
        elif '十关注' in page_str:
            logger.info("在关注界面,退出")
            keyevent('back')
            return 2, False
        elif '以后再说' in page_str and '加入书架' in page_str:
            logger.info("在小说详情界面,退出")
            self.touch_target("以后再说")
            return 2, False
        elif '暂不开启' in page_str:
            logger.info("弹出对话框")
            self.touch_target("暂不开启")
            return 2, False
        elif '看视频签到' in page_str and '已经连续签到' in page_str:
            logger.info("在视频签到界面")
            self.touch_target("看视频签到")
            return 2, False
        elif '评价并收下金币' in page_str:
            logger.info("在视频评价界面")
            self.touch_target("评价并收下金币")
            return 2, False
        elif '软件商店' in page_str and '文件管理' in page_str:
            self.touch_target("抖音极速版")
            logger.info("重新进抖音")
            return 5, False
        if "赚钱任务" in page_str:
            logger.info("返回任务界面")
            if self.youyou:
                self.youyou = False
                self.touch_target("赚钱任务")

        if self.first_start and "详情" in page_str:
            self.touch_target("详情")
            return 2, False

        self.first_start = False

        if not self.have_value:
            values = re.findall(r"(\d{2})分(\d{2})秒", page_str)
            if values:
                value = values[0]
                try:
                    self.wastetime_value = int(value[0]) * 60 + int(value[1])
                    th = Thread(target=self.check_wastetime_task)
                    th.deamon = True
                    th.start()
                    # th.join()
                    self.have_value = True
                except Exception as e:
                    print(e)
                logger.info(self.wastetime_value)

        for t in self.touch_back_list:
            if t in page_str:
                keyevent("back")

        # for t in self.touch_2_back_list:
        #     if t in page_str:
        #         self.touch_target(t)
        #         sleep(2)
        #         logger.info("返回")
        #         keyevent("back")
        #         return 2, False

        if '开宝箱得金' in page_str:
            self.touch_target("开宝箱得金币")
            return 2, False

        if '看广告视频再赚' in page_str:
            self.touch_target("看广告视频再赚")
            return 2, False

        if '恭喜你获得' in page_str and '看广告视频' in page_str:
            self.touch_target("看广告视频")
            self.poco(text='广告').wait_for_appearance()
            self.guanggao = True
            return 2, False
        # if "点击立得" in page_str:
        #     touch_target("点击立得")
        #     sleep(2)
        #     keyevent("back")
        #     # return "task"
        while self.give_coin:
            # while 1:
            self.page_text, self.box = self.ocr_page()
            page_str = ''.join(self.page_text)
            if "免费送" in page_str:
                self.touch_target('免费送')
                self.give_coin = False
                return 2, False
            else:
                swipe(self.start_point, self.end_point, duration=0.5)
                sleep(1)
        if "立即签到" in page_str:
            self.touch_target("立即签到")
            return 2, False
        if "好的" in page_str:
            self.touch_target("好的")
            return 2, False
        # 这里有问题等待会有超时现象
        if "吃饭打卡" in page_str and "去领取" in page_str:
            if page_str.find("去领取") > page_str.find("吃饭打卡"):
                logger.info("ocr点击 吃饭打卡")
                self.touch_target('去领取')
                return 10, False

        if "签到奖励已翻倍" in page_str:
            self.touch_target('签到奖励已翻倍')
            return 2, False

        elif "已连续签到" in page_str and not "明白签到" in page_str and not "明日签到" in page_str and not "明天签到" in page_str and not "明关签到" in page_str:
            self.touch_target('已连续签到')
            # keyevent('back')
            return 2, False

        if "现在可领" in page_str:
            self.touch_target("去打卡")
            return 2, False

        # elif "你也得金" in page_str:
        #     self.give_coin = True
        #     self.touch_target("你也得金")
        #     return 2

        if "去发布" in page_str and not "发布视频日记" in page_str:
            self.touch_target("去发布")
            self.youyou = True
            return 2, False

        if '我的待发布动态' in page_str and "发动态" in page_str:
            self.touch_target('发动态')
            self.youyou = True
            return 2, False

        if "发布100" in page_str:
            self.touch_target("发布100")
            self.youyou = True
            # 点击后，直接再处理
            return 2, False

        if "看广告赚金" in page_str and "去领取" in page_str:
            logger.info("看广告赚金")
            self.touch_target("看广告赚金")
            return 2, False

        elif "看游戏视频" in page_str and "去赚" in page_str and "浏览30秒" in page_str:
            logger.info("看游戏视频")
            self.touch_target("看游戏视频")
            return 2, False

        # # 加入逛商城，要优先做
        # elif "逛商城" in page_str and "去商城" in page_str and "60秒" in page_str:
        #     self.shop = True
        #     if self.wastetime_task_begin:
        #         logger.info("逛商城")
        #         self.touch_target("去商城")
        #         return 2, False

        elif "活动规则" in page_str or "明日签到必得额外大奖" in page_str:
            self.touch_target("详情")
            self.wastetime_task_begin = True
            return 2, False

        elif "邀请记录" in page_str:
            keyevent("back")
        elif "去搜索" in page_str:
            self.search = True
            self.touch_target("去搜索")
            # keyevent("back")
            return 2, False
        elif "去小岛" in page_str and not self.in_island and self.islandClick:
            self.touch_target("去小岛")
            start = time.time()
            while not self.poco(text="规则").exists():
                if time.time() - start > self.timeout:
                    logger.info("touch 去小岛 判定超时")
                    swipe(self.start_point_1, self.end_point_1, duration=1)
                    self.in_island = False
                    break
            else:
                self.islandClick = False
                self.in_island = True
                # return 2, False
                sleep(2)
            return 2, False
        # # 去逛街 失效
        # if "去逛街" in page_str:
        #     self.touch_target("去逛街")
        #     self.go_shopping = True
        #     return 2
        # 这是看视频的，其次
        if not self.video_done:
            if "看视频" in page_str and "去赚钱" in page_str and "2分钟" in page_str:
                video_money = re.findall(r"最高得(\d+)金.*?2分钟", page_str)
                if video_money:
                    video_money = int(video_money[0])
                    logger.info(f"看视频 已达节点：{video_money}")
                    if video_money < self.video_coin:
                        self.video = True
                        if not self.shop and not self.novel and not self.live and self.wastetime_task_begin and self.wastetime_value:
                            logger.info("看视频")
                            self.touch_target("看视频")
                    else:
                        self.video = False
                        self.video_done = True

        # 这是看小说的，再次
        if not self.novel_done:
            if "看更多" in page_str or "看小说" in page_str:
                self.novel = True
                if not self.shop and self.wastetime_task_begin:
                    logger.info("看小说")
                    if "看更多" in page_str:
                        self.touch_target("看更多")
                    elif "看小说" in page_str:
                        self.touch_target("看小说")
                    start = time.time()
                    while not self.poco(textMatches='推荐榜.*?').exists():
                        if time.time() - start > self.timeout:
                            logger.error("书架载入失败")
                            return 2, True
                            # raise TimeoutError("书架载入失败")
                    return 2, False
        # 看直播的最次执行
        if not self.live_done:
            if "立刻取" in page_str:
                # 这个是看直播优先最低
                # if "已取回" in page_str:
                total_num = 10
                temp_num = re.findall(rf'.*?([0-9])/{total_num}.*?', page_str)
                if not temp_num:
                    total_num = 20
                    temp_num = re.findall(rf'.*?(\d+)/{total_num}.*?',
                                          page_str)
                if temp_num:
                    if int(temp_num[0]) < total_num:
                        self.live = True
                        logger.info(f'已领取箱子{int(temp_num[0])}个')
                        if self.wastetime_task_begin and self.wastetime_value and not self.novel:
                            logger.info("看直播")
                            self.touch_target("立刻取")
                            self.watching_live = True
                            logger.info("休眠60秒，等待直播载入")
                            # sleep(60)
                            # self.poco("m.l.live.plugin:id/emoji_entry"
                            #           ).wait_for_appearance()
                            # logger.info("")
                            return 60, True
                    else:
                        print(f"已完成 看直播 任务")
                        self.live_done = True
            elif '看直播开宝箱' in page_str:
                print(f"已完成 看直播 任务")
                self.live_done = True
                self.live = False
        if "看视频再领" in page_str and "恭喜打卡成功" in page_str:
            self.touch_target("看视频再领")
            return 2, False
        # self.live_done = True
        return 2, True

    def touch_target(self, target_text: str):
        """
        target_text:目标文字
        
        raw_list:所有已识别字符串
        
        box:所有已识别的box
        """
        logger.info(f"触摸↓↓↓↓{target_text}↓↓↓↓")
        _, i = max_option_match(target_text, self.page_text)
        top_left_x = int(self.box[i][0][0])
        top_left_y = int(self.box[i][0][1])
        bottom_right_x = int(self.box[i][2][0])
        bottom_right_y = int(self.box[i][2][1])
        # touch1 = cv2.rectangle(self.dev.snapshot(), (top_left_x, top_left_y),
        #                        (bottom_right_x, bottom_right_y), (0, 255, 0),
        #                        2)
        # cv2.imwrite('./img/touch1.png', touch1)
        touch(((top_left_x + (bottom_right_x - top_left_x) // 2),
               (top_left_y + (bottom_right_y - top_left_y) // 2)))
        # screen = dev.snapshot()
        sleep(2)
        return self.page_text[i]
        # cv2.imwrite('./img/touch2.png', self.dev.snapshot())

    def check_wastetime_task(self):
        """
        检查是否该停止-->瞎看<--进度

        Args:
            wastetimevalue (_type_): _description_
        """
        timeout = self.wastetime_value
        while timeout:
            print("宝箱倒计时---------------------->",
                  timeout,
                  self.wastetime_task_begin,
                  end='\r')
            sleep(1)
            timeout -= 1
        self.wastetime_value = 0
        self.have_value = False
        self.wastetime_task_begin = False

    def loop(self):
        while 1:
            # 夜里刷视频
            while time.localtime().tm_hour < 7:
                print(time.localtime().tm_hour,
                      time.localtime().tm_min,
                      end='\r')
                sleep(random.randint(5, 10))
                swipe(self.start_point, self.end_point)
            # 白天做任务，优化完可以夜里一起做
            if self.poco_judge_page():
                secs, to_swipe = self.ocr_judge_page()
                if to_swipe:
                    logger.info("↑" * 10)
                    swipe(self.start_point, self.end_point)
                if secs:
                    sleep(secs)
            sleep(2)


def to_main_page():
    pass


def start(dev):
    dy = douyin(dev)
    dy.loop()


if __name__ == '__main__':
    devs = get_devices_list()
    print(devs)
    p_list = []
    if '5e4ada56' in devs:
        start('5e4ada56')
    # for d in devs:
    #     p = Process(target=start, args=(d, ))
    #     p_list.append(p)
    #     p.start()
    # for p in p_list:
    #     p.join()
    # start()
    # cv2.imwrite('./img/start.png', dev.snapshot())
    # print(poco(textMatches=r'\d+秒.*?').exists())
    # keyevent("back")
    # # keyevent("back")
    # sleep(2)
    # cv2.imwrite('./img/start2.png', dev.snapshot())
    # sys.exit(0)
    # stop_app("com.ss.android.ugc.aweme.lite")

    # while True:
    #     sleep(random.randint(10, 20))
    #     swipe(start_point, end_point)
